<template>
	<div class="zh-info"
		v-loading="loading.status"
		:element-loading-text="loading.txt"
	>
		<div class="zh-info-g">
				<h3>本校风采</h3>
			<div class="i_elegantDemeanor clear">
				<div class="i_companyImg fl">
					<img v-if="selectFileOrNot || ruleForm.pictrue != ''" :src="previewImgURL" class="avatar">
				</div>
				<div class="i_companyProfile" v-html="ruleForm.content"></div>
			</div>
		</div>
		<div class="zhSowing-form">
			<h3>配置信息</h3>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm"  label-width="80px">
				<el-form-item label="模块名称" prop="name" >
					<el-input class="link-name" v-model="ruleForm.name" maxlength="20" placeholder="20个字符内"></el-input>
				</el-form-item>
				<el-form-item label="上传图片">
					<!-- <uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @files-submitted="fileSubmit"  @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail"  class="uploader-example">
						    <uploader-unsupport></uploader-unsupport>
						    <uploader-btn 
						    :directory="false" 
						    :attrs="attrs" 
						    v-if="selectFileShow"  
						    :single="true">
							    选择图片(仅支持图片格式)
							</uploader-btn>
						    <uploader-list  v-if="!selectFileShow"></uploader-list>
						</uploader> -->
					<uploader 
						:options="uploadOptions" 
						:autoStart="false" 
						ref="uploader" 
						:file-status-text="statusText"
						@file-added="fileAddImg"
						@file-removed="fileRemoved" 
						@file-success="fileSuccess" 
						@file-error="fileFail"  
						class="uploader-example">
							<uploader-unsupport></uploader-unsupport>
							<uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">上传图片（支持图片格式的文件）</uploader-btn>
							<uploader-list></uploader-list>
					</uploader>
				</el-form-item>
				<el-form-item label="正文内容" prop="content" >
					<tinymce 
                        id="d1" 
                        :plugins="plugins" 
                        :other_options="options" 
                        :toolbar1="toolbar1" 
                        :toolbar2="toolbar2"  
                        :images_upload_handler="images_upload_handler" 
                        v-model="ruleForm.content"
                     @editorInit="editorInit">
                     </tinymce>
                    <div class="tinymce-num"><i>{{tinymceNum}}</i> / 10000</div>
				</el-form-item> 
				<el-form-item>
					<el-button size="medium" plain @click="resetForm('ruleForm')" type="primary">重置</el-button>
					<el-button size="medium" type="primary" @click="submitForm('ruleForm')">保存</el-button>
				</el-form-item>
			</el-form>
		</div>
        
		<el-dialog
			title="图片设置"
			:visible.sync="cropperViews"
			:width="cropperWidth"
			custom-class="croppering"
			:before-close="clearFilet"
			:close-on-click-modal="false"
            :close-on-press-escape="false">
			<div class="croppering">
				<div class="cropper">
					<vueCropper
						ref="cropper"
						:img="imgOption.img"
						:outputSize="imgOption.size"
						:outputType="imgOption.outputType"
						:info="true"
						:full="imgOption.full"
						:canMove="imgOption.canMove"
						:canMoveBox="imgOption.canMoveBox"
						:fixedBox="imgOption.fixedBox"
						:original="imgOption.original"
						:autoCrop="imgOption.autoCrop"
						:autoCropWidth="imgOption.autoCropWidth"
						:autoCropHeight="imgOption.autoCropHeight"
						:centerBox="imgOption.centerBox"
						:high="imgOption.high"
						:infoTrue="imgOption.infoTrue"
						:enlarge="imgOption.enlarge">
					</vueCropper>
				</div>
                <div slot="footer" class="dialog-footer cropper_btn">
                    <el-button  @click="clearFilet()">取消</el-button>
                    <el-button type="primary" @click="finish('base64')">确定</el-button>
                </div>
			</div>
		</el-dialog>
	</div>	
</template>

<script>
	import axios from '../../../tools/axios';
	import tinymce from 'vue-tinymce-editor';
    import { VueCropper }  from 'vue-cropper';
    import {dataURLtoFile, uploaderFileFail} from './../../../tools/tool';
	
	export default{
		data(){
			return {
				cropperViews: false, // 是否显示图片裁剪的模态框
                cropperWidth: '950px', // 容器的宽度
                imgOption: { // vue-cropper 参数配置
                    img: '', // 裁剪图片的地址
                    size: 1, // 裁剪生成图片的质量
                    full: false, // 是否输出原图比例的截图
                    outputType: 'png', //输出图片格式
                    canMove: true, //能否拖动图片
                    fixedBox: true, //截图框固定大小
                    original: true, //否显示原始宽高
                    canMoveBox: true,  //能否拖动截图框
                    autoCrop: true, //autoCrop 是否自动生成截图框
                    // 只有自动截图开启 宽度高度才生效
                    autoCropWidth: 330,
                    autoCropHeight: 200,
                    centerBox: false, //截图框是否限制在图片里
                    high: true //是否根据dpr生成适合屏幕的高清图片
                },
				activeName: '1',
				loading:{
					status:false,
					txt:'获取数据...'
                },
                imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
				plugins:['paste','fullscreen','link' ],
				toolbar1: 'paste,fullscreen,link',
				toolbar2: 'table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | link | removeformat',
				options:{
					images_upload_handler:this.images_upload_handler,
	                language_url: '/static/tinymce_languages/zh_CN.js',
	                images_upload_url:this.BASE_URL+'/api/resource/res_upload_permanent',
	                paste_data_images: true,                  // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
	                paste_convert_word_fake_lists: false,     // 插入word文档需要该属性
					paste_webkit_styles: 'all',
					paste_merge_formats: true,
					nonbreaking_force_tab: false,
                    paste_auto_cleanup_on_paste: false,
                    convert_urls: false,
					font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
                        仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                    `,
	            },

				statusText: {
					success: '上传成功',  
					error: '上传出错',  
					uploading: '正在上传...',  
					paused: '暂停',  
					waiting: '等待上传'  
                },
                tinymceNum: 0, // 编辑器初始长度
				selectFileOrNot:false,  //是否选中文件
				uploadOrNot:false, 		//是否已经上传
				uploadInfo:{
					file_name:'',
					file_path:'',
					file_size:0
				},
				attrs: {
					accept: ['image/*']
				},
				uploadOptions: {
					target: this.BASE_URL+'/api/resource/res_upload',
					testChunks: false,
					headers:{Authorization : `Bearer `+this.$g.access_token},
				},

				selectFileShow:true,//是否显示选择文件按钮
				uploadRetryTimes:100,//文件最大重传次数
				previewImgURL:'',
				ruleForm: {
					name: '',
					content: '',
				},
				rules: {
					name: [
						{ required: true, message: '请输入名称' },
						{ min: 3, max: 20, message: '长度在 3 到 20 个字符' },
						{pattern:/^\S+$/,message:'不能包含空格'}
					],
					content: [{ validator: this.checkContent, trigger: ['blur', 'change'], required: true }]
				},
				defaultImg: null,
			}
		},
		created(){
			//等待timeyce加载完成
			setTimeout(()=>{
				this.getNewsInfo();
			}, 500)			
        },
        watch: {
            /**
             * 监听富文本的内容长度，判断是否超出规定内容
             */
            'ruleForm.content'(newVal, oldVal) {
                setTimeout(() => {
                    let body = document.getElementById('d1_ifr').contentWindow.document.getElementsByTagName('body')[0].textContent;
                    let newLen = body.replace(/\s/g, '').length;
                    let oldLen = this.tinymceNum;

                    // 判断邮件长度是否超过 10000
                    if (newLen > 10000) {
                        this.$message.warning('内容最大长度不可以超过 10000 个字');
                        this.tinymceNum = oldLen;
                        this.ruleForm.content = oldVal;
                    } else {
                        this.tinymceNum = newLen;
                    }
                }, 300);
            }
        },
		methods: {
            /**
             * 验证输入内容
             */
            checkContent(rule, value, callback) {
                if (!isEmpty(value)) {
                    return callback(new Error('请填写内容'));
                } else {
                    let body = document.getElementById('d1_ifr').contentWindow.document.getElementsByTagName('body')[0].textContent
                    let newLen = body.replace(/\s/g, '').length;

                    if (newLen < 3 || newLen > 10000) {
                        return callback(new Error('长度在 3 到 10000 个字符'));
                    } else {
                        callback()
                    }
                }
            },
            /**
             * 编辑器初始化
             */
            editorInit() {
                // 修改输入框内文字与边界的宽
                let dom = document.getElementById('d1_ifr').contentWindow.document.getElementById('tinymce');
                dom.style.margin = "8px 25px 45px";
            },
			//清空上传控件列表的数据
            clearFilet() {
                this.cropperViews = false;
                this.$refs.uploader.uploader.cancel();    
				this.previewImgURL = this.BASE_URL + this.ruleForm.picture;
			},
			//图片裁剪后替换原图片
            finish(type) {
                if (type === 'blob') {
			        this.$refs.cropper.getCropBlob((data) => {
			            this.$refs.uploader.uploader.files[0].file = data;
                        this.$refs.uploader.uploader.files[0].size = data.size;
                        this.$refs.uploader.uploader.fileList[0].file = data;
                        this.$refs.uploader.uploader.fileList[0].size = data.size;

                        this.previewImgURL = window.URL.createObjectURL(data);
                        this.selectFileOrNot = true;
                        this.selectFileShow = false;
                        this.cropperViews = false;
                        this.selectFileShowImg = false;
                        this.selectFileOrNotImg = true;
			        })
			    } else {
			        this.$refs.cropper.getCropData((data) => {
                        let modelView = dataURLtoFile(data, this.$refs.uploader.uploader.fileList[0].name, 'png');

                        if (modelView.size > 10240000) {
                            this.$message.warning('只允许上传10M以内的文件');
                            this.clearFilet();
                        } else {
							this.$refs.uploader.uploader.files[0].file = modelView;
							this.$refs.uploader.uploader.files[0].size = modelView.size;
							this.$refs.uploader.uploader.fileList[0].file = modelView;
                            this.$refs.uploader.uploader.fileList[0].size = modelView.size;
                            
                            this.$refs.uploader.uploader.fileList[0].fileType = 'image/png';
                            this.$refs.uploader.uploader.files[0].fileType = 'image/png';
                            this.$refs.uploader.uploader.fileList[0].name = this.$refs.uploader.uploader.fileList[0].name.split(/(.*)\.[^.]+/).join('') + '.png';
                            this.$refs.uploader.uploader.files[0].name = this.$refs.uploader.uploader.fileList[0].name.split(/(.*)\.[^.]+/).join('') + '.png';
                            this.$refs.uploader.uploader.fileList[0].relativePath = this.$refs.uploader.uploader.fileList[0].relativePath.split(/(.*)\.[^.]+/).join('') + '.png';
                            this.$refs.uploader.uploader.files[0].relativePath = this.$refs.uploader.uploader.fileList[0].relativePath.split(/(.*)\.[^.]+/).join('') + '.png';
							this.$refs.uploader.uploader.fileList[0].uniqueIdentifier = modelView.size+"-"+this.$refs.uploader.uploader.fileList[0].name;
							this.$refs.uploader.uploader.fileList[0].chunks[0].endByte = modelView.size;

							this.previewImgURL = data;
							this.defaultImg = deep_clone(data);
							this.selectFileOrNot = true;
							this.selectFileShow = false;

                            this.cropperViews = false;
                            // this.selectFileShowImg = false;
							// this.selectFileOrNotImg = true;
                        }
			        })
			    }
			},
			fileAddImg(file, fileList) {
                let file_type = file.fileType.toLocaleLowerCase();

                if (!this.imageType.includes(file_type)) {
                    this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');

                    this.$refs.uploader.uploader.cancel();
                } else {
                    this.imgOption.img = window.URL.createObjectURL(file.file)
					this.cropperViews = true;
                }
			},
			//上传成功的事件  
			fileSuccess (rootFile, file, message, chunk) { 
                var mess = eval('(' + message + ')');
                mess = handleResponseData( mess );
                
			 	if(parseInt( mess.data.status ) === 1 ){
					this.uploadOrNot = true;
					this.uploadInfo.file_name = mess.data.file_name;
					this.uploadInfo.file_path = mess.data.file_path;
					this.uploadInfo.post_fix = mess.data.post_fix;
					this.ruleForm.picture = mess.data.file_path;
					this.saveNews();
					this.clearFilet();
					this.getNewsInfo();
			  	}
			},
			fileRemoved(file){
				this.selectFileOrNot = false;
				this.selectFileShow = true;
				this.previewImgURL = this.BASE_URL + this.ruleForm.picture;
			},
			fileFail(rootFile, file, message, chunk) {
                uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
			},
			// 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
			images_upload_handler (blobInfo, success, failure) {
				if( blobInfo.blob().type.indexOf('image/')  === -1 ){
					failure('只允许上传图片格式的文件')
				}else if( blobInfo.blob().size >  10240000 ) {
			     	failure('图片大小不能超过10M')
			   }else{
					let formData = new FormData();
			            formData.append( 'file', blobInfo.blob() , blobInfo.filename() );
				    let succ = ( data => {
                        // data.data =  data.data.data;
			    		success(this.BASE_URL + data.data.data.file_path)
					});
					let fail = ( data => {
                        data.data =  data.data.data;
			    		failure(data.data.data.message)
					});
					//******************************TODO 不知为何要重新create*****************//
					const instance = axios.create({
						headers:{
							Authorization:`Bearer ${this.$g.access_token}`,
							DecisionPlatform :` ${this.$g.access_token}`,
							token : sessionStorage.getItem('token'),
						},
			          	withCredentials: true,
			         }) 
				    instance.post('api/resource/res_upload_permanent',formData).then( succ ).catch(fail)
				}
			},	
			getNewsInfo (){
				this.loading.status = true;
				this.loading.txt = '获取数据...';
				// 重写成功回调 
				let success = (data => {
					this.loading.status = false;
					if( !is_empty( data.data )){
						this.ruleForm = {
							name: data.data.name,
							picture:data.data.picture,
							content: data.data.content,
						}

						this.previewImgURL  = this.BASE_URL +　data.data.picture;
					}

				});
				let fail  = ( data => {
					this.loading.status = false;
					$this.$message.error( data.msg ) ; 
				})
  				this.$ajax.get('api/setting/school_culture',{params:{},func:{ success:success, fail:fail }})
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.loading.status = true;
						this.loading.txt = '保存数据...';
						if( this.selectFileOrNot ){
							this.fileUpload();
						}else{
							this.saveNews();
						}
					} else {
						return false;
					}
				});
            },
            /**
             * 重置为默认的状态
             * @param {String} formName 表单 ref
             */
			resetForm(formName) {
				this.selectFileOrNot = false;
				this.selectFileShow = true;
				this.previewImgURL = '';
				this.clearFilet();
				this.$refs[formName].resetFields();
				// this.ruleForm.picture = '';
                this.$forceUpdate(); //强制渲染
                
                this.getNewsInfo()
			},
			saveNews(){
		    	let success = ( data => {
		    		this.loading.status = false;
		    		this.$message.success( data.msg) ;
					this.$refs.uploader.uploader.fileList = [];
		    		this.selectFileShow = true;
				});
				
				this.$ajax.post('api/setting/school_culture',this.ruleForm,{func:{success:success}})
			},
			//过滤文件格式
			fileSubmit(files, fileList, event){
				for (var i = 0 ; i < fileList.length ; i++ ) {
					if( fileList[i].fileType.indexOf('image/') === -1 ){
						this.$message.warning('只允许上传图片格式的文件')
						this.$refs.uploader.uploader.removeFile( fileList[i] );
					}else{
						if( this.$refs.uploader.uploader.fileList.length  > 1  ){
							//删除第一张图片
							this.$refs.uploader.uploader.removeFile( this.$refs.uploader.uploader.fileList[0] );
						}
						this.previewImgURL = window.URL.createObjectURL(fileList[i].file)
						this.uploadInfo.file_size = fileList[i].size;
						this.selectFileOrNot = true;
						this.selectFileShow = false;
					}
				}
			},
			fileUpload(){
				this.$refs.uploader.uploader.upload();
			},
		},
		components:{
			tinymce,
			VueCropper
		}
	}
</script>

<style lang="scss">
.zh-info {
    #d1_ifr {
        height: 350px !important;
    }
    
    .tinymce-num {
        position: absolute;
        right: 0;
        bottom: 1px;
        display: block;
        padding-right: 35px;
        width: calc(100% - 1px);
        text-align: right;
        font-size: 12px;
        color: #999;
        background: #F9F9F9;
        box-sizing: border-box;
    }

    .mce-statusbar.mce-container.mce-panel.mce-stack-layout-item.mce-last {
        display: none;
    }

    .mce-tinymce.mce-container.mce-panel[role=application] >div >div:first-child >div >div:first-child   {
        display: none;
    }

    .mce-tinymce.mce-container.mce-panel[role=application] >div >div:first-child >div >div:last-child >div >div:first-child {
        display: none;
    }

	.zh-info-g{
		max-width: 1000px;
		padding: 20px 50px;
		background: #EEEEEE;
	}

	.i_elegantDemeanor{
		padding: 35px 40px;
		background: #fff;
		margin: 10px 0 30px;
	}
	.i_companyImg{
		width: 250/920*100%;
		height: 180px;
		overflow: hidden;
		margin-right: 40px;
		>img{
			width: 100%;
            height: 100%;
            object-fit: contain;
		}
	}

	.i_companyProfile{
		width: 780/1200*100%;
		height: 200px;
		font-size: 14px;
		overflow: hidden;
        overflow-y: auto;
		// line-height: 20px;
	}

	.zhSowing-form{

		.up{
			border: 0;
			color: #7C9BB8;
			background: #DEEFFF;
			border-radius: 3px;
			margin-right: 20px;
		}
		.upTXT{
			font-size: 14px;
		}
		.link-name{
			width: 470px;	
			>input{
				border-radius: 0;
			}
		}
		.nubxx{
			position: absolute;
            right: 15px;
            bottom: 0px;
            font-size: 12px;
            color: #999;

			>i{
				color: #333;
			}
		}
		
		.uploader-list {
		    .uploader-file-pause {
		      display: none !important;
		    }
		    .uploader-file-status {
		      text-indent: 0;
		    }
 		 }
	}

	.croppering {
		.cropper {
			height: 500px;
			
			>div{
				height: 100%;
			}
		}

		.dialog-footer {
			padding: 35px 0;
			text-align: center;

			button {
				padding: 10px 30px;
			}
		}

		.vue-cropper {
			position: relative;
			width: 100%;
			height: 500px;
			box-sizing: border-box;
			user-select: none;
			-webkit-user-select: none;
			-moz-user-select: none;
			-ms-user-select: none;
			direction: ltr;
			touch-action: none;
			text-align: left;
			background-image: url("");
		}

		.cropper-box,
		.cropper-box-canvas,
		.cropper-drag-box,
		.cropper-crop-box,
		.cropper-face {
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			user-select: none;
		}

		.cropper-box-canvas img {
			position: relative;
			text-align: left;
			user-select: none;
			transform: none;
			max-width: none;
			max-height: none;
		}

		.cropper-box {
			overflow: hidden;
		}

		.cropper-move {
			cursor: move;
		}

		.cropper-crop {
			cursor: crosshair;
		}

		.cropper-modal {
			background: rgba(0, 0, 0, 0.5);
		}
		
		.cropper-view-box {
			display: block;
			overflow: hidden;
			width: 100%;
			height: 100%;
			outline: 1px solid #39f;
			outline-color: rgba(51, 153, 255, 0.75);
			user-select: none;
		}

		.cropper-view-box img {
			user-select: none;
			text-align: left;
			max-width: none;
			max-height: none;
		}

		.cropper-face {
			top: 0;
			left: 0;
			background-color: #fff;
			opacity: 0.1;
		}

		.crop-info {
			position: absolute;
			left: 0px;
			min-width: 65px;
			text-align: center;
			color: white;
			line-height: 20px;
			background-color: rgba(0, 0, 0, 0.8);
			font-size: 12px;
		}

		.crop-line {
			position: absolute;
			display: block;
			width: 100%;
			height: 100%;
			opacity: 0.1;
		}

		.line-w {
			top: -3px;
			left: 0;
			height: 5px;
			cursor: n-resize;
		}

		.line-a {
			top: 0;
			left: -3px;
			width: 5px;
			cursor: w-resize;
		}

		.line-s {
			bottom: -3px;
			left: 0;
			height: 5px;
			cursor: s-resize;
		}

		.line-d {
			top: 0;
			right: -3px;
			width: 5px;
			cursor: e-resize;
		}

		.crop-point {
			position: absolute;
			width: 8px;
			height: 8px;
			opacity: 0.75;
			background-color: #39f;
			border-radius: 100%;
		}

		.point1 {
			top: -4px;
			left: -4px;
			cursor: nw-resize;
		}

		.point2 {
			top: -5px;
			left: 50%;
			margin-left: -3px;
			cursor: n-resize;
		}

		.point3 {
			top: -4px;
			right: -4px;
			cursor: ne-resize;
		}

		.point4 {
			top: 50%;
			left: -4px;
			margin-top: -3px;
			cursor: w-resize;
		}

		.point5 {
			top: 50%;
			right: -4px;
			margin-top: -3px;
			cursor: e-resize;
		}

		.point6 {
			bottom: -5px;
			left: -4px;
			cursor: sw-resize;
		}

		.point7 {
			bottom: -5px;
			left: 50%;
			margin-left: -3px;
			cursor: s-resize;
		}

		.point8 {
			bottom: -5px;
			right: -4px;
			cursor: se-resize;
		}
	}
}
</style>